package com.qianlou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qianlou.common.result.PagedResult;
import com.qianlou.mapper.CandidateCustomMapper;
import com.qianlou.mapper.CandidateMapper;
import com.qianlou.pojo.Candidate;
import com.qianlou.pojo.bo.CandidateBO;
import com.qianlou.pojo.vo.CandidateVO;
import com.qianlou.service.CandidateService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 应聘者表 服务实现类
 * </p>
 *
 * @author James
 * @since 2025-04-26
 */
@Service
public class CandidateServiceImpl extends ServiceImpl<CandidateMapper, Candidate> implements CandidateService {

    @Resource
    private CandidateMapper candidateMapper;

    @Resource
    private CandidateCustomMapper candidateCustomMapper;

    @Override
    public void createOrUpdate(CandidateBO candidateBO) {
        Candidate candidate = new Candidate();
        BeanUtils.copyProperties(candidateBO, candidate);
        candidate.setUpdatedTime(LocalDateTime.now());
        if (StringUtils.isBlank(candidate.getId())) {
            candidate.setCreatedTime(LocalDateTime.now());
            candidateMapper.insert(candidate);
        } else {
            candidateMapper.updateById(candidate);
        }
    }

    @Override
    public PagedResult selectCandidateList(String realName, String mobile, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("realName", realName);
        paramsMap.put("mobile", mobile);
        List<CandidateVO> candidateList = candidateCustomMapper.selectCandidateList(paramsMap);
        return PagedResult.of(candidateList, page);
    }

    @Override
    public Candidate getByMobile(String mobile) {
        return getCandidateByField("mobile", mobile);
    }

    @Override
    public Candidate getByEmail(String email) {
        return getCandidateByField("email", email);
    }

    private Candidate getCandidateByField(String fieldName, String fieldValue) {
        QueryWrapper<Candidate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, fieldValue);
        Candidate candidate = candidateMapper.selectOne(queryWrapper);
        return candidate;
    }
}
